window.onload = function() {
    layui.use(['form', 'upload', 'jquery', 'element','layer'], function() {
        var upload = layui.upload,
            form = layui.form,
            element = layui.element,
            $ = layui.jquery;

        var uploader = {
            'data': {
                'token': '',
                'uploadDomain': '',
                'domain': ''
            },
            // 'complete':function(res){
            //     var url="http://"+uploader.data.domain +"/"+ res.key;
            //     $(".pic3").attr("src",url);
            //     $(".pic3-val").val(res.key);
            // },
            'error': function() {
                console.dir(arguments);
            },
            // 分片上传时的进度展示功能在此书写.
            'next': function(response) {
                // var chunks = response.chunks || [];
                // var total = response.total;
            },
            'init': function() {
                $.ajax({
                    'url': '/upload/get-token',
                    'type': 'POST',
                    'dataType': 'json',
                    'success': function(data) {
                        if (data.code != 200) {
                            Utils.layer.alert(data.msg);
                            return false;
                        }
                        uploader.data.token = data.data.token; // token
                        uploader.data.domain = data.data.domain; // 显示域名
                        // uploader.data.uploadDomain = 'idv093d.qiniudns.com';    // 上传域名
                        // console.log(uploader.data.token)
                    }
                });
            },
            'eventBind': function() {
                this.init();
                $('.pic-card3').on('change', function(e) {
                    var fileList = e.target.files[0];
                    UpladFile(fileList, '.pic3', '.hidden-pic3')
                });
                $('.default').on('change', function(e) {
                    var fileList = e.target.files[0];
                    UpladFile(fileList, '.pic-pic', '')
                });
                $('body').on("change", ".pic-card4", function(e) {
                    var fileList = e.target.files[0];
                    var idx = $(this).attr("indexs");
                    UpladFile(fileList, '', '', idx)
                })

                function UpladFile(ele, showPic, hiddenPic, index) {
                    var fileObj = ele; // js 获取文件对象
                    var formData = new FormData(); // FormData 对象
                    if (fileObj.size / 1024 > 200) { //大于200k，进行压缩上传
                        photoCompress(fileObj, { quality: 0.9 }, function(base64Codes) {
                            //console.log("压缩后：" + base.length / 1024 + " " + base);
                            var bl = convertBase64UrlToBlob(base64Codes);
                            formData.append("file", bl, "file_" + Date.parse(new Date()) + ".jpg"); // 文件对象
                            var token = uploader.data.token;
                            var config = {
                                useCdnDomain: true,
                                disableStatisticsReport: false,
                                region: qiniu.region.z0
                            };
                            var putExtra = {
                                fname: "",
                                params: {},
                                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
                            };
                            // var file = this.files[0];
                            bl.name = fileObj.name;
                            var file = bl;
                            if (TestFileSuffix(file.name) < 0) {
                                Utils.layer.msg('请上传 jpg/png 类型图片');
                                return;
                            }
                            var observable;
                            if (file) {
                                // var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                                var files = file;
                                var key1 = file.name;
                                var key = key1.split(".")[0] + Date.parse(new Date()) + "." + key1.split(".")[1];
                                putExtra.params["x:name"] = key.split(".")[0];
                                // 配置完成的数组.
                                if (showPic == '.pic-pic') {
                                    var subObject = {
                                        next: uploader.next,
                                        error: uploader.error,
                                        complete: function(res) {
                                            var url = "http://" + uploader.data.domain + "/" + res.key;
                                            var newImg = "<div style='display:inline-block;'><div class='detail-img' style='width:150px;height:150px;position:relative;margin:0 10px;'>"
                                            newImg += "<img src='" + url + "' style='width:100%;height:100%;'>"
                                            newImg += "<input type='hidden' name='img_url' class='hidden-picc' value='" + res.key + "'>"
                                            newImg += "<div class='xxx' style='position:absolute;top:0;right:0;width:20px;height:20px;line-height:20px;text-align:center;background:#ddd;cursor:pointer;'>X</div>"
                                            newImg += "</div></div>";
                                            $(".imgs").append(newImg);
                                            delbanner()
                                        }
                                    };
                                } else if (showPic == '.pic3') {
                                    var subObject = {
                                        next: uploader.next,
                                        error: uploader.error,
                                        complete: function(res) {
                                            var url = "http://" + uploader.data.domain + "/" + res.key;
                                            $(showPic).attr("src", url).css('display', 'block');
                                            $(hiddenPic).val(res.key);
                                        }
                                    };
                                } else {
                                    var subObject = {
                                        next: uploader.next,
                                        error: uploader.error,
                                        complete: function(res) {
                                            var showpic = '.imgindex' + index;
                                            $(showpic).val(res.key);
                                        }
                                    };
                                }

                                var subscription;
                                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                                observable = qiniu.upload(files, key, token, putExtra, config);
                                subscription = observable.subscribe(subObject);
                                // subscription.unsubscribe();  // 取消上传.
                            }
                        });
                    } else {
                        var token = uploader.data.token;
                        var config = {
                            useCdnDomain: true,
                            disableStatisticsReport: false,
                            region: qiniu.region.z0
                        };
                        var putExtra = {
                            fname: "",
                            params: {},
                            mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
                        };
                        var file = fileObj
                        // bl.name=fileObj.name;
                        // var file=bl;
                        if (TestFileSuffix(file.name) < 0) {
                            Utils.layer.msg('请上传 jpg/png 类型图片');
                            return;
                        }
                        var observable;
                        if (file) {
                            // var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                            var files = file;
                            var key1 = file.name;
                            var key = key1.split(".")[0] + Date.parse(new Date()) + "." + key1.split(".")[1];
                            putExtra.params["x:name"] = key.split(".")[0];
                            // 配置完成的数组.
                            if (showPic == '.pic-pic') {
                                var subObject = {
                                    next: uploader.next,
                                    error: uploader.error,
                                    complete: function(res) {
                                        var url = "http://" + uploader.data.domain + "/" + res.key;
                                        var newImg = "<div style='display:inline-block;'><div class='detail-img' style='width:150px;height:150px;position:relative; margin-right:10px;'>"
                                        newImg += "<img src='" + url + "' style='width:100%;height:100%;'>"
                                        newImg += "<input type='hidden' name='img_url' class='hidden-picc' value='" + res.key + "'>"
                                        newImg += "<div class='xxx' style='position:absolute;top:0;right:0;width:20px;height:20px;line-height:20px;text-align:center;background:#ddd;cursor:pointer;'>X</div>"
                                        newImg += "</div></div>";
                                        $(".imgs").append(newImg);
                                        delbanner()
                                    }
                                };
                            } else if (showPic == '.pic3') {
                                var subObject = {
                                    next: uploader.next,
                                    error: uploader.error,
                                    complete: function(res) {
                                        var url = "http://" + uploader.data.domain + "/" + res.key;
                                        $(showPic).attr("src", url).css('display', 'block');
                                        $(hiddenPic).val(res.key);
                                    }
                                };
                            } else {
                                var subObject = {
                                    next: uploader.next,
                                    error: uploader.error,
                                    complete: function(res) {
                                        var showpic = '.imgindex' + index;
                                        $(showpic).val(res.key);
                                    }
                                };
                            }

                            var subscription;
                            // 调用sdk上传接口获得相应的observable，控制上传和暂停
                            observable = qiniu.upload(files, key, token, putExtra, config);
                            subscription = observable.subscribe(subObject);
                            // subscription.unsubscribe();  // 取消上传.
                        }
                    }
                }

                function photoCompress(file, w, objDiv) {
                    var ready = new FileReader();
                    /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
                    ready.readAsDataURL(file);
                    ready.onload = function() {
                        var re = this.result;
                        canvasDataURL(re, w, objDiv)
                    }
                }

                function canvasDataURL(path, obj, callback) {
                    var img = new Image();
                    img.src = path;
                    img.onload = function() {
                        var that = this;
                        // 默认按比例压缩
                        var w = that.width,
                            h = that.height,
                            scale = w / h;
                        w = obj.width / 1.2 || w / 1.2;
                        h = obj.height / 1.2 || (w / scale) / 1.2;
                        var quality = 0.8; // 默认图片质量为0.7
                        //生成canvas
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        // 创建属性节点
                        var anw = document.createAttribute("width");
                        anw.nodeValue = w;
                        var anh = document.createAttribute("height");
                        anh.nodeValue = h;
                        canvas.setAttributeNode(anw);
                        canvas.setAttributeNode(anh);
                        ctx.drawImage(that, 0, 0, w, h);
                        // 图像质量
                        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
                            quality = obj.quality;
                        }
                        // quality值越小，所绘制出的图像越模糊
                        var base64 = canvas.toDataURL('image/jpeg', quality);
                        // 回调函数返回base64的值
                        callback(base64);
                    }
                }
                /**  
                 * 将以base64的图片url数据转换为Blob  
                 * @param urlData  
                 *            用url方式表示的base64图片数据  
                 */
                function convertBase64UrlToBlob(urlData) {
                    var arr = urlData.split(','),
                        mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]),
                        n = bstr.length,
                        u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new Blob([u8arr], { type: mime });
                }

            }
        };

        $('#introduction').on('keyup', function() {
            var indexs = 220;
            var texts = $(this).val().length;
            indexs = indexs - texts;
            if (indexs < 0) {
                Utils.layer.alert('已超过220个字符');
            }
            $('.introduction_count').html(texts);
        })
        $('#introduction').keyup();

        $('.menu-name').on('keyup', function() {
            var num = $(this).val().length;
            if (num > 45) {
                Utils.layer.msg("字数不能超过45字")
            }
            $('.menu_name_count').text(num)
        })
        $('.menu-name').keyup();



        function delbanner($this) {
            $('.xxx').unbind('click').on('click', function() {
                if (confirm('确定删除当前图片？')) {
                    $(this).parent().parent().remove();
                }
            })
        }
        delbanner()

        //三级联动
        form.on('select(one)',function(data){
            var id=data.value;
            $('.twoclass').html('');
            $('.threeclass').html('<option value="0">请选择三级分类</option>');
            if(id!=0){
                changeclassAjax('.twoclass', id, '二')
            }else{
                form.render('select')
            }
        })
        form.on('select(two)',function(data){
            var id=data.value;
            $('.threeclass').html('');
            if(id!=0){
                changeclassAjax('.threeclass', id, '三')
            }else{
                form.render('select');
            }
        })

        function changeclassAjax(calsss, id, num) {
            $.ajax({
                'url': '/goods/get-tree',
                'type': 'POST',
                'dataType': 'json',
                'data': { id: id },
                'success': function(data) {
                    if (data.code != 200) {
                        Utils.layer.alert(data.msg);
                        return false;
                    } else {
                        var option = '<option value="0">请选择' + num + '级分类</option>';
                        $.each(data.data, function(indexe, value) {
                            option += '<option value="' + value.id + '">' + value.tree_name + '</option>'
                        });
                        $(calsss).append(option);
                        form.render('select');
                    }
                }
            });
        }

        function DataLength(fData) {
            var intLength = 0
            for (var i = 0; i < fData.length; i++) {
                if ((fData.charCodeAt(i) < 0) || (fData.charCodeAt(i) > 255))
                    intLength = intLength + 2
                else
                    intLength = intLength + 1
            }
            return intLength
        }


        $(document).ready(function() {

            uploader.eventBind();

            //传递数据
            $(".btn-last-googs").on("click", function() {
                var newattr = [];
                var thd = [],
                    tby = [];
                // $(".thead").find('th').each(function(i){
                //     var th_val=$(".thead").find('th').eq(i).text();
                //     thd.push(th_val);
                // })
                $(".tbody").find('tr').each(function(i) {
                    var td_val = []
                    $(".tbody").find('tr').eq(i).find('.need').each(function(j) {
                        var needVal = $(".tbody").find('tr').eq(i).find('.need').eq(j).val();
                        if (needVal) {
                            td_val.push(needVal);
                        } else {
                            td_val.push(0);
                        }

                    })
                    tby.push(td_val)
                })

                var twoid = $(".twoclass option:selected").val(); //二级分类
                var oneid = $(".oneclass option:selected").val(); //一级分类
                var threeid = $(".threeclass option:selected").val(); //一级分类
                var goods_name = $(":input[name='goods_name']").val();
                var type = $(":input[name='goods_type']:checked").val();
                var key = $(":input[name='key']").val();
                var goods_id = $(":input[name='goods_id']").val();
                var list_img = $(":input[name='list_img']").val();
                var attr_name = $(":input[name='attr_name']").val();
                var introduction = $("#introduction").val();
                // var content = UE.getEditor('editor').getContent();
                var freight = $(":input[name='freight']").val();
                freight = freight > 0 ? freight : 0;
                var banner = new Array();

                var charNum = $(".menu-name").val().length;
                var attr_describe = [];

                $('.hidden-picc').each(function($i) {
                    banner[$i] = $(this).val();
                });

                
                flag = true;
                if (goods_name == "") {
                    Utils.layer.msg("请输入商品名称");
                    flag = false;
                } else if (charNum > 45) {
                    Utils.layer.msg("商品名称不能超过45字");
                    flag = false;
                } else if (list_img == '') {
                    Utils.layer.msg("请上传封面图");
                    flag = false;
                } else if (banner.length == 0) {
                    Utils.layer.msg("请添加详情图");
                    flag = false;
                } else if (threeid == 0) {
                    Utils.layer.msg("请选择商品三级分类");
                    flag = false;
                }
                $('.attr_describe div').each(function(idx){
                  var key = $(this).find('input[name="key"]').val();
                  var val = $(this).find('input[name="val"]').val();
                  var id = $(this).attr('data-id');
                  if(key == "" && val == ""){
                    return;
                  }else if(key == "" || val == ""){
                    Utils.layer.msg("请完善属性描述");
                    flag = false;
                    return;
                  }else{
                    attr_describe.push({
                      key: key,
                      val: val,
                      id: id ? id : 0
                    })
                  }
                })
                data = {
                    'goods_name': goods_name,
                    'goods_type': type,
                    'key': key,
                    'list_img': list_img,
                    'introduction': introduction,
                    'attr_name': attr_name,
                    'banner': banner,
                    'two_tree_id': twoid,
                    'one_tree_id': oneid,
                    'three_tree_id': threeid,
                    'freight': freight,
                    tby: tby,
                    'goods_id': goods_id,
                    attr_describe:attr_describe
                };
                if (flag) {
                    $.ajax({
                        'url': '/supplier/update',
                        'type': 'POST',
                        'dataType': 'json',
                        'data': data,
                        'success': function(data) {
                            if (data.code != 200) {
                                Utils.layer.msg(data.msg);
                                return false;
                            } else {
                                Utils.layer.msg(data.msg);
                                setTimeout(function() {
                                    location.href = "/supplier/index";
                                }, 1000);
                            }

                        }
                    });
                }
            });
        })

// 属性描述
      var addAttrDescribe = $('.add_attr_describe');
      var attrDescribe = $('.attr_describe');
      addAttrDescribe.click(function(){
        var inputs = attrDescribe.find('div').last().find('input');
        if(inputs.eq(0).val() == "" && inputs.eq(1).val() == ""){
          return
        }else{
          var htmlStr = '<div><span><input type="text" name="key" class="layui-input" placeholder="属性" /><input type="text" name="val" class="layui-input" placeholder="描述" /></span><b class="layui-btn del_attr_describe">删除</b></div>';
          $(htmlStr).appendTo(attrDescribe)
          delAttrDescribe()
          showAttrDescribe()
        }
      })
      delAttrDescribe()

      function delAttrDescribe(){
        $('.del_attr_describe').unbind('click').click(function(){
          var that = $(this);
          Utils.layer.confirm('确定要删除当前属性描述?', {
            btn: ['确认', '取消'],
            btn1: function(index, layero){
              that.parent('div').remove();
              showAttrDescribe()
              Utils.layer.closeAll()
            }
          })
        })
      }
      function showAttrDescribe(){
        if(attrDescribe.find('div').length == 0){
          attrDescribe.hide()
        }else{
          attrDescribe.show()
        }
      }
    })
}